package com.winning.pmph.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.winning.pmph.entity.ActivityItem;
import com.winning.pmph.entity.TaskItem;
import com.winning.pmph.mapper.ActivityItemMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Component
public class ActivityItemService extends ServiceImpl<ActivityItemMapper, ActivityItem> {
    @Resource
    ActivityItemMapper activityItemMapper;
    @Resource
    ActivityItemService activityItemService;
    @Resource
    TaskItemService taskItemService;

    public void addTaskItemList(String id, String editType, String selectedActivityIds, String taskId, String remark, JSONObject searchParams, String username) {
        List<ActivityItem> activityItems = null;
        // 批量修订;
        if (Objects.equals("multi", editType)) {
            activityItems = activityItemService.lambdaQuery().in(ActivityItem::getId, JSON.parseArray(selectedActivityIds, String.class)).list();
        } else {
            // 一键修订, 查询当前搜索条件的知识;
            Page<ActivityItem> activityItemPage = activityItemService
                    .lambdaQuery()
                    .eq(ActivityItem::getStatus, "undistributed")
                    .eq(StringUtils.isNotBlank(searchParams.getString("id")), ActivityItem::getActivityId, searchParams.getString("id"))
                    .like(StringUtils.isNotEmpty(searchParams.getString("name")), ActivityItem::getKnowledgeName, searchParams.getString("name"))
                    .eq(ActivityItem::getDeleted, ActivityItem.DELETED_NO)
                    .eq(StringUtils.isNotEmpty(searchParams.getString("knowledgeLibId")), ActivityItem::getKnowledgeLibId, searchParams.getString("knowledgeLibId"))
                    .orderByDesc(ActivityItem::getUpdatedTime)
                    .orderByAsc(ActivityItem::getId)
                    .page(new Page<>());
            activityItems = activityItemPage.getRecords();
        }
        for (ActivityItem activityItem : activityItems) {
            TaskItem taskItem = new TaskItem();
            taskItem.setTaskId(taskId);
            taskItem.setKnowledgeId(activityItem.getKnowledgeId());
            taskItem.setName(activityItem.getKnowledgeName());
            taskItem.setRemark(remark);
            taskItem.setStatus(TaskItem.STATUS_NOT_COMMIT);
            taskItemService.saveOrUpdate(taskItem);
            activityItem.setStatus(ActivityItem.DISTRIBUTION);
            activityItem.setTaskId(taskItem.getTaskId());
            activityItemService.saveOrUpdate(activityItem);
        }
    }
}
